package com.cloudwave.trailends.compo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.widget.Toast;

import com.cloudwave.trailends.AppContext;
import com.cloudwave.trailends.Constants;
import com.cloudwave.trailends.domain.RidingLine;
import com.cloudwave.trailends.domain.User;
import com.cloudwave.trailends.service.RidingService;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.db.table.DbModel;
import com.lidroid.xutils.exception.DbException;
import com.umeng.analytics.MobclickAgent;

/**
 * @description 基础抽象Activity
 * @author DolphinBoy
 * @email dolphinboyo@gmail.com
 * @date 2013-8-2 @time 下午9:27:00
 * 
 */

public class BaseActivity extends Activity {
	private static final String TAG = "BaseActivity";
	
	protected boolean isfinished = false;
	
	protected BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
        	BaseActivity.this.finish();
        }
    };
	
    @Override
    protected void onResume() {
    	super.onResume();
        IntentFilter filter = new IntentFilter();
        filter.addAction(RidingService.SYS_EXIT);
        this.registerReceiver(this.broadcastReceiver, filter);
        
        //用于友盟统计
        MobclickAgent.onResume(this);
        Log.i(TAG, "onPause---友盟统计开始");
    }
    
    @Override
	protected void onPause() {
    	super.onPause();
		//用于友盟统计
		MobclickAgent.onPause(this);
		Log.i(TAG, "onPause---友盟统计结束");
	}

    protected void exitApp(Context context) {
		Intent intentExit = new Intent();
		intentExit.setAction(RidingService.SYS_EXIT);
		context.sendBroadcast(intentExit);
    }
    
    /**
     * 更新用户数据
     * @param context
     * @param user
     * @return
     */
    protected boolean statUserData(Context context) {
    	User user = ((AppContext) getApplication()).loadLoginUser();
		if ( user != null ) {
			DbUtils dbu = DbUtils.create(context, Constants.DB_NAME);
			try {
				long count = dbu.count(Selector.from(RidingLine.class).where("crudStatus_", "!=", 3));
				if ( count == 0 ) {
					user.setTotalRidingLine(0);
					user.setTotalMileage(0);
					user.setTotalLinePoint(0);
					user.setTotalRidingTime(0);
				} else {
					DbModel dbModel = dbu.findDbModelFirst(Selector.from(RidingLine.class).select("COUNT(id_) AS num,SUM(totalMileage_) AS totalMileage,SUM(totalPoint_) AS totalPoint,SUM(totalTime_) AS totalTime").where("crudStatus_", "!=", 3));
					if ( !dbModel.getDataMap().isEmpty() ) {
						int num = dbModel.getInt("num");
						float totalMileage = 0;
						if ( !dbModel.isEmpty("totalMileage") ) {
							totalMileage = dbModel.getFloat("totalMileage");
						}
						int totalPoint = 0;
						if ( !dbModel.isEmpty("totalPoint") ) {
							totalPoint = dbModel.getInt("totalPoint");
						}
						long totalTime = 0;
						if ( !dbModel.isEmpty("totalTime") ) {
							totalTime = dbModel.getInt("totalTime");
						}
						
						user.setTotalRidingLine(num);
						user.setTotalMileage(totalMileage);
						user.setTotalLinePoint(totalPoint);
						user.setTotalRidingTime(totalTime);
					}
				}
				
				((AppContext) getApplication()).updateLoginUser(user);
				return true;
			} catch (DbException e) {
				Toast.makeText(context, "更新统计数据失败~_~", Toast.LENGTH_SHORT).show();
				Log.e(TAG, e.getMessage());
				return false;
			}
		}
		return true;
	}
    
//    protected boolean statUserData(Context context) {
//    	User user = ((AppContext) getApplication()).loadLoginUser();
//		if ( user != null ) {
//			DbUtils dbu = DbUtils.create(context, Constants.DB_NAME);
//			try {
//				DbModel dbModel = dbu.findDbModelFirst(Selector.from(RidingLine.class).select("COUNT(id_) AS num,SUM(totalMileage_) AS totalMileage,SUM(totalPoint_) AS totalPoint,SUM(totalTime_) AS totalTime").where("isNow_", "=", 0));
//				if (dbModel != null && !dbModel.getDataMap().isEmpty()) {
//					int count = dbModel.getInt("num");
//					float totalMileage = dbModel.getFloat("totalMileage");
//					int totalPoint = dbModel.getInt("totalPoint");
//					long totalTime = dbModel.getInt("totalTime");
//					
//					user.setTotalRidingLine(count);
//					user.setTotalMileage(totalMileage);
//					user.setTotalLinePoint(totalPoint);
//					user.setTotalRidingTime(totalTime);
//					
//					((AppContext) getApplication()).setLoginUser(user);
//				}
//				return true;
//			} catch (DbException e) {
//				Toast.makeText(context, "更新统计数据失败~_~", Toast.LENGTH_SHORT).show();
//				Log.e(TAG, e.getMessage());
//				return false;
//			}
//		}
//		return true;
//	}
    
	//通用弹框
	
	
	//菜单弹框
//	protected void initPopuptWindow1(OnItemClickListener clickListener) {
//		Log.i(TAG, "initPopuptWindow");
//		dialogLayout = (LinearLayout) LayoutInflater.from(TripNowActivity.this).inflate(
//				R.layout.dialog_menu, null);
//		dialogListView = (ListView) dialogLayout.findViewById(R.id.lv_menu);
//		dialogListView.setAdapter(new ArrayAdapter<String>(TripNowActivity.this,
//				R.layout.dialog_menu_item, R.id.tv_menu_text, menus));
//		
//		popupWindow = new PopupWindow(TripNowActivity.this);
//		popupWindow.setBackgroundDrawable(new BitmapDrawable());
//		popupWindow
//				.setWidth(getWindowManager().getDefaultDisplay().getWidth() / 2);
//		popupWindow.setHeight(150);
//		popupWindow.setOutsideTouchable(true);
//		popupWindow.setFocusable(true);
//		popupWindow.setContentView(dialogLayout);
//		
//		// showAsDropDown会把里面的view作为参照物，所以要那满屏幕parent
//		// popupWindow.showAsDropDown(findViewById(R.id.tv_title), x, 10);
//		popupWindow.showAtLocation(parent, Gravity.CENTER
//						| Gravity.CENTER, x, y);//需要指定Gravity，默认情况是center.
//		
//		dialogListView.setOnItemClickListener(clickListener);
//		
//		
//	}
	
	//通用Loader弹框
	
    
    //目前界面层次比较浅，暂时不用返回退出功能
//	@Override
//	public void onBackPressed()
//	{
//		//super.onBackPressed();
//		if (isfinished) {
//			exitApp(this);
//			finish();
//		} else {
//			Toast.makeText(this, "再按一次返回键退出", Toast.LENGTH_SHORT).show();
//			new Thread() {
//				public void run() {
//					isfinished = true;
//					try {
//						Thread.sleep(2000);
//						isfinished = false;
//					} catch (InterruptedException e) {
//						e.printStackTrace();
//					}
//				};
//			}.start();
//		}
//	}
    
    @Override
    protected void onDestroy() {
        this.unregisterReceiver(this.broadcastReceiver);
        super.onDestroy();
    }
}
